<?php
/**
 *
 * 版权所有：安德玛(underArmour)
 * 作    者：1554324405@qq.com
 * 日    期：2020-05-20
 * 版    本：1.0.0
 * 功能说明：新闻公告控制器。
 *
 **/
namespace Api\Controller;

class NewsController extends ComController
{
    
    /**
     * 列表页
     */
    public function index()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $pagesize = isset($_GET['pagesize']) ? intval($_GET['pagesize']) : '10';
        $m = M('news');
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $m->count();
        $list = $m->order('px asc,t desc')->field('id,title,t')->limit($offset . ',' . $pagesize)->select();
        foreach ($list as $key=>&$val){
            $list[$key]['t'] = date('Y-m-d H:i:s',$list[$key]['t']);
            $list[$key]['title'] = str_replace('<br>', '', $list[$key]['title']);
        }
        $page = new \Think\Page($count, $pagesize);
        $page->show();
        $page_arr = array(
            'totalCount'=>intval($count),
            'pageSize'=>$pagesize,
            'totalPage'=>$page->totalPages,
            'currPage'=>intval($p)
        );
        $this->res['data']['page'] = $page_arr;
        $this->res['data']['list'] = $list;
        $this->response($this->res,'json');
    }
    
    /**
     * 详情页
     */
    public function detail()
    {
        $id = I('get.id','','htmlentities');
        if(!$id){
            $this->res['code'] = 101;
            $this->res['msg'] = '请传入id';
            $this->response($this->res,'json');
        }
        $info = M('news')->where('id='.$id)->find();
        if(empty($info)){
            $this->res['code'] = 102;
            $this->res['msg'] = '记录不存在';
            $this->response($this->res,'json');
        }
        $info['t'] = date('Y-m-d H:i:s',$info['t']);
        $info['title'] = str_replace('<br>', '', $info['title']);
        $info['content'] = richTextAbsoluteUrl($info['content'],C('URL'));
        if($info['type'] == 1){
            $info['type'] = '新闻公告';
        }else{
            $info['type'] = '系统消息';
        }
        // 浏览量+1
        M('news')->where('id='.$id)->setInc('n',1);
        // 标记消息已读
        $user_message = M('user_message')->where(array('relation_id'=>$id))->find();
        if(!empty($user_message)){
            $count = M('user_readmessage')->where(array('uid'=>$this->user['id'],'msg_id'=>$user_message['id']))->count();
            if($count == 0){
                M('user_readmessage')->data(array('msg_id'=>$user_message['id'],'uid'=>$this->user['id']))->add();
            }          
        }
        $this->res['data']['info'] = $info;
        $this->response($this->res,'json');
    }
    
}